connectionpool.py 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033
  1. from __future__ import absolute_import
  2. import errno
  3. import logging
  4. import sys
  5. import warnings
  6. from socket import error as SocketError, timeout as SocketTimeout
  7. import socket
  8. from .exceptions import (
  9. ClosedPoolError,
  10. ProtocolError,
  11. EmptyPoolError,
  12. HeaderParsingError,
  13. HostChangedError,
  14. LocationValueError,
  15. MaxRetryError,
  16. ProxyError,
  17. ReadTimeoutError,
  18. SSLError,
  19. TimeoutError,
  20. InsecureRequestWarning,
  21. NewConnectionError,
  22. )
  23. from .packages.ssl_match_hostname import CertificateError
  24. from .packages import six
  25. from .packages.six.moves import queue
  26. from .connection import (
  27. port_by_scheme,
  28. DummyConnection,
  29. HTTPConnection,
  30. HTTPSConnection,
  31. VerifiedHTTPSConnection,
  32. HTTPException,
  33. BaseSSLError,
  34. )
  35. from .request import RequestMethods
  36. from .response import HTTPResponse
  37. from .util.connection import is_connection_dropped
  38. from .util.request import set_file_position
  39. from .util.response import assert_header_parsing
  40. from .util.retry import Retry
  41. from .util.timeout import Timeout
  42. from .util.url import (
  43. get_host,
  44. parse_url,
  45. Url,
  46. _normalize_host as normalize_host,
  47. _encode_target,
  48. )
  49. from .util.queue import LifoQueue
  50. xrange = six.moves.xrange
  51. log = logging.getLogger(__name__)
  52. _Default = object()
  53. # Pool objects
  54. class ConnectionPool(object):
  55. """
  56. Base class for all connection pools, such as
  57. :class:`.HTTPConnectionPool` and :class:`.HTTPSConnectionPool`.
  58. .. note::
  59. ConnectionPool.urlopen() does not normalize or percent-encode target URIs
  60. which is useful if your target server doesn't support percent-encoded
  61. target URIs.
  62. """
  63. scheme = None
  64. QueueCls = LifoQueue
  65. def __init__(self, host, port=None):
  66. if not host:
  67. raise LocationValueError("No host specified.")
  68. self.host = _normalize_host(host, scheme=self.scheme)
  69. self._proxy_host = host.lower()
  70. self.port = port
  71. def __str__(self):
  72. return "%s(host=%r, port=%r)" % (type(self).__name__, self.host, self.port)
  73. def __enter__(self):
  74. return self
  75. def __exit__(self, exc_type, exc_val, exc_tb):
  76. self.close()
  77. # Return False to re-raise any potential exceptions
  78. return False
  79. def close(self):
  80. """
  81. Close all pooled connections and disable the pool.
  82. """
  83. pass
  84. # This is taken from http://hg.python.org/cpython/file/7aaba721ebc0/Lib/socket.py#l252
  85. _blocking_errnos = {errno.EAGAIN, errno.EWOULDBLOCK}
  86. class HTTPConnectionPool(ConnectionPool, RequestMethods):
  87. """
  88. Thread-safe connection pool for one host.
  89. :param host:
  90. Host used for this HTTP Connection (e.g. "localhost"), passed into
  91. :class:`httplib.HTTPConnection`.
  92. :param port:
  93. Port used for this HTTP Connection (None is equivalent to 80), passed
  94. into :class:`httplib.HTTPConnection`.
  95. :param strict:
  96. Causes BadStatusLine to be raised if the status line can't be parsed
  97. as a valid HTTP/1.0 or 1.1 status line, passed into
  98. :class:`httplib.HTTPConnection`.
  99. .. note::
  100. Only works in Python 2. This parameter is ignored in Python 3.
  101. :param timeout:
  102. Socket timeout in seconds for each individual connection. This can
  103. be a float or integer, which sets the timeout for the HTTP request,
  104. or an instance of :class:`urllib3.util.Timeout` which gives you more
  105. fine-grained control over request timeouts. After the constructor has
  106. been parsed, this is always a `urllib3.util.Timeout` object.
  107. :param maxsize:
  108. Number of connections to save that can be reused. More than 1 is useful
  109. in multithreaded situations. If ``block`` is set to False, more
  110. connections will be created but they will not be saved once they've
  111. been used.
  112. :param block:
  113. If set to True, no more than ``maxsize`` connections will be used at
  114. a time. When no free connections are available, the call will block
  115. until a connection has been released. This is a useful side effect for
  116. particular multithreaded situations where one does not want to use more
  117. than maxsize connections per host to prevent flooding.
  118. :param headers:
  119. Headers to include with all requests, unless other headers are given
  120. explicitly.
  121. :param retries:
  122. Retry configuration to use by default with requests in this pool.
  123. :param _proxy:
  124. Parsed proxy URL, should not be used directly, instead, see
  125. :class:`urllib3.connectionpool.ProxyManager`"
  126. :param _proxy_headers:
  127. A dictionary with proxy headers, should not be used directly,
  128. instead, see :class:`urllib3.connectionpool.ProxyManager`"
  129. :param \\**conn_kw:
  130. Additional parameters are used to create fresh :class:`urllib3.connection.HTTPConnection`,
  131. :class:`urllib3.connection.HTTPSConnection` instances.
  132. """
  133. scheme = "http"
  134. ConnectionCls = HTTPConnection
  135. ResponseCls = HTTPResponse
  136. def __init__(
  137. self,
  138. host,
  139. port=None,
  140. strict=False,
  141. timeout=Timeout.DEFAULT_TIMEOUT,
  142. maxsize=1,
  143. block=False,
  144. headers=None,
  145. retries=None,
  146. _proxy=None,
  147. _proxy_headers=None,
  148. **conn_kw
  149. ):
  150. ConnectionPool.__init__(self, host, port)
  151. RequestMethods.__init__(self, headers)
  152. self.strict = strict
  153. if not isinstance(timeout, Timeout):
  154. timeout = Timeout.from_float(timeout)
  155. if retries is None:
  156. retries = Retry.DEFAULT
  157. self.timeout = timeout
  158. self.retries = retries
  159. self.pool = self.QueueCls(maxsize)
  160. self.block = block
  161. self.proxy = _proxy
  162. self.proxy_headers = _proxy_headers or {}
  163. # Fill the queue up so that doing get() on it will block properly
  164. for _ in xrange(maxsize):
  165. self.pool.put(None)
  166. # These are mostly for testing and debugging purposes.
  167. self.num_connections = 0
  168. self.num_requests = 0
  169. self.conn_kw = conn_kw
  170. if self.proxy:
  171. # Enable Nagle's algorithm for proxies, to avoid packet fragmentation.
  172. # We cannot know if the user has added default socket options, so we cannot replace the
  173. # list.
  174. self.conn_kw.setdefault("socket_options", [])
  175. def _new_conn(self):
  176. """
  177. Return a fresh :class:`HTTPConnection`.
  178. """
  179. self.num_connections += 1
  180. log.debug(
  181. "Starting new HTTP connection (%d): %s:%s",
  182. self.num_connections,
  183. self.host,
  184. self.port or "80",
  185. )
  186. conn = self.ConnectionCls(
  187. host=self.host,
  188. port=self.port,
  189. timeout=self.timeout.connect_timeout,
  190. strict=self.strict,
  191. **self.conn_kw
  192. )
  193. return conn
  194. def _get_conn(self, timeout=None):
  195. """
  196. Get a connection. Will return a pooled connection if one is available.
  197. If no connections are available and :prop:`.block` is ``False``, then a
  198. fresh connection is returned.
  199. :param timeout:
  200. Seconds to wait before giving up and raising
  201. :class:`urllib3.exceptions.EmptyPoolError` if the pool is empty and
  202. :prop:`.block` is ``True``.
  203. """
  204. conn = None
  205. try:
  206. conn = self.pool.get(block=self.block, timeout=timeout)
  207. except AttributeError: # self.pool is None
  208. raise ClosedPoolError(self, "Pool is closed.")
  209. except queue.Empty:
  210. if self.block:
  211. raise EmptyPoolError(
  212. self,
  213. "Pool reached maximum size and no more connections are allowed.",
  214. )
  215. pass # Oh well, we'll create a new connection then
  216. # If this is a persistent connection, check if it got disconnected
  217. if conn and is_connection_dropped(conn):
  218. log.debug("Resetting dropped connection: %s", self.host)
  219. conn.close()
  220. if getattr(conn, "auto_open", 1) == 0:
  221. # This is a proxied connection that has been mutated by
  222. # httplib._tunnel() and cannot be reused (since it would
  223. # attempt to bypass the proxy)
  224. conn = None
  225. return conn or self._new_conn()
  226. def _put_conn(self, conn):
  227. """
  228. Put a connection back into the pool.
  229. :param conn:
  230. Connection object for the current host and port as returned by
  231. :meth:`._new_conn` or :meth:`._get_conn`.
  232. If the pool is already full, the connection is closed and discarded
  233. because we exceeded maxsize. If connections are discarded frequently,
  234. then maxsize should be increased.
  235. If the pool is closed, then the connection will be closed and discarded.
  236. """
  237. try:
  238. self.pool.put(conn, block=False)
  239. return # Everything is dandy, done.
  240. except AttributeError:
  241. # self.pool is None.
  242. pass
  243. except queue.Full:
  244. # This should never happen if self.block == True
  245. log.warning("Connection pool is full, discarding connection: %s", self.host)
  246. # Connection never got put back into the pool, close it.
  247. if conn:
  248. conn.close()
  249. def _validate_conn(self, conn):
  250. """
  251. Called right before a request is made, after the socket is created.
  252. """
  253. pass
  254. def _prepare_proxy(self, conn):
  255. # Nothing to do for HTTP connections.
  256. pass
  257. def _get_timeout(self, timeout):
  258. """ Helper that always returns a :class:`urllib3.util.Timeout` """
  259. if timeout is _Default:
  260. return self.timeout.clone()
  261. if isinstance(timeout, Timeout):
  262. return timeout.clone()
  263. else:
  264. # User passed us an int/float. This is for backwards compatibility,
  265. # can be removed later
  266. return Timeout.from_float(timeout)
  267. def _raise_timeout(self, err, url, timeout_value):
  268. """Is the error actually a timeout? Will raise a ReadTimeout or pass"""
  269. if isinstance(err, SocketTimeout):
  270. raise ReadTimeoutError(
  271. self, url, "Read timed out. (read timeout=%s)" % timeout_value
  272. )
  273. # See the above comment about EAGAIN in Python 3. In Python 2 we have
  274. # to specifically catch it and throw the timeout error
  275. if hasattr(err, "errno") and err.errno in _blocking_errnos:
  276. raise ReadTimeoutError(
  277. self, url, "Read timed out. (read timeout=%s)" % timeout_value
  278. )
  279. # Catch possible read timeouts thrown as SSL errors. If not the
  280. # case, rethrow the original. We need to do this because of:
  281. # http://bugs.python.org/issue10272
  282. if "timed out" in str(err) or "did not complete (read)" in str(
  283. err
  284. ): # Python < 2.7.4
  285. raise ReadTimeoutError(
  286. self, url, "Read timed out. (read timeout=%s)" % timeout_value
  287. )
  288. def _make_request(
  289. self, conn, method, url, timeout=_Default, chunked=False, **httplib_request_kw
  290. ):
  291. """
  292. Perform a request on a given urllib connection object taken from our
  293. pool.
  294. :param conn:
  295. a connection from one of our connection pools
  296. :param timeout:
  297. Socket timeout in seconds for the request. This can be a
  298. float or integer, which will set the same timeout value for
  299. the socket connect and the socket read, or an instance of
  300. :class:`urllib3.util.Timeout`, which gives you more fine-grained
  301. control over your timeouts.
  302. """
  303. self.num_requests += 1
  304. timeout_obj = self._get_timeout(timeout)
  305. timeout_obj.start_connect()
  306. conn.timeout = timeout_obj.connect_timeout
  307. # Trigger any extra validation we need to do.
  308. try:
  309. self._validate_conn(conn)
  310. except (SocketTimeout, BaseSSLError) as e:
  311. # Py2 raises this as a BaseSSLError, Py3 raises it as socket timeout.
  312. self._raise_timeout(err=e, url=url, timeout_value=conn.timeout)
  313. raise
  314. # conn.request() calls httplib.*.request, not the method in
  315. # urllib3.request. It also calls makefile (recv) on the socket.
  316. if chunked:
  317. conn.request_chunked(method, url, **httplib_request_kw)
  318. else:
  319. conn.request(method, url, **httplib_request_kw)
  320. # Reset the timeout for the recv() on the socket
  321. read_timeout = timeout_obj.read_timeout
  322. # App Engine doesn't have a sock attr
  323. if getattr(conn, "sock", None):
  324. # In Python 3 socket.py will catch EAGAIN and return None when you
  325. # try and read into the file pointer created by http.client, which
  326. # instead raises a BadStatusLine exception. Instead of catching
  327. # the exception and assuming all BadStatusLine exceptions are read
  328. # timeouts, check for a zero timeout before making the request.
  329. if read_timeout == 0:
  330. raise ReadTimeoutError(
  331. self, url, "Read timed out. (read timeout=%s)" % read_timeout
  332. )
  333. if read_timeout is Timeout.DEFAULT_TIMEOUT:
  334. conn.sock.settimeout(socket.getdefaulttimeout())
  335. else: # None or a value
  336. conn.sock.settimeout(read_timeout)
  337. # Receive the response from the server
  338. try:
  339. try:
  340. # Python 2.7, use buffering of HTTP responses
  341. httplib_response = conn.getresponse(buffering=True)
  342. except TypeError:
  343. # Python 3
  344. try:
  345. httplib_response = conn.getresponse()
  346. except BaseException as e:
  347. # Remove the TypeError from the exception chain in
  348. # Python 3 (including for exceptions like SystemExit).
  349. # Otherwise it looks like a bug in the code.
  350. six.raise_from(e, None)
  351. except (SocketTimeout, BaseSSLError, SocketError) as e:
  352. self._raise_timeout(err=e, url=url, timeout_value=read_timeout)
  353. raise
  354. # AppEngine doesn't have a version attr.
  355. http_version = getattr(conn, "_http_vsn_str", "HTTP/?")
  356. log.debug(
  357. '%s://%s:%s "%s %s %s" %s %s',
  358. self.scheme,
  359. self.host,
  360. self.port,
  361. method,
  362. url,
  363. http_version,
  364. httplib_response.status,
  365. httplib_response.length,
  366. )
  367. try:
  368. assert_header_parsing(httplib_response.msg)
  369. except (HeaderParsingError, TypeError) as hpe: # Platform-specific: Python 3
  370. log.warning(
  371. "Failed to parse headers (url=%s): %s",
  372. self._absolute_url(url),
  373. hpe,
  374. exc_info=True,
  375. )
  376. return httplib_response
  377. def _absolute_url(self, path):
  378. return Url(scheme=self.scheme, host=self.host, port=self.port, path=path).url
  379. def close(self):
  380. """
  381. Close all pooled connections and disable the pool.
  382. """
  383. if self.pool is None:
  384. return
  385. # Disable access to the pool
  386. old_pool, self.pool = self.pool, None
  387. try:
  388. while True:
  389. conn = old_pool.get(block=False)
  390. if conn:
  391. conn.close()
  392. except queue.Empty:
  393. pass # Done.
  394. def is_same_host(self, url):
  395. """
  396. Check if the given ``url`` is a member of the same host as this
  397. connection pool.
  398. """
  399. if url.startswith("/"):
  400. return True
  401. # TODO: Add optional support for socket.gethostbyname checking.
  402. scheme, host, port = get_host(url)
  403. if host is not None:
  404. host = _normalize_host(host, scheme=scheme)
  405. # Use explicit default port for comparison when none is given
  406. if self.port and not port:
  407. port = port_by_scheme.get(scheme)
  408. elif not self.port and port == port_by_scheme.get(scheme):
  409. port = None
  410. return (scheme, host, port) == (self.scheme, self.host, self.port)
  411. def urlopen(
  412. self,
  413. method,
  414. url,
  415. body=None,
  416. headers=None,
  417. retries=None,
  418. redirect=True,
  419. assert_same_host=True,
  420. timeout=_Default,
  421. pool_timeout=None,
  422. release_conn=None,
  423. chunked=False,
  424. body_pos=None,
  425. **response_kw
  426. ):
  427. """
  428. Get a connection from the pool and perform an HTTP request. This is the
  429. lowest level call for making a request, so you'll need to specify all
  430. the raw details.
  431. .. note::
  432. More commonly, it's appropriate to use a convenience method provided
  433. by :class:`.RequestMethods`, such as :meth:`request`.
  434. .. note::
  435. `release_conn` will only behave as expected if
  436. `preload_content=False` because we want to make
  437. `preload_content=False` the default behaviour someday soon without
  438. breaking backwards compatibility.
  439. :param method:
  440. HTTP request method (such as GET, POST, PUT, etc.)
  441. :param body:
  442. Data to send in the request body (useful for creating
  443. POST requests, see HTTPConnectionPool.post_url for
  444. more convenience).
  445. :param headers:
  446. Dictionary of custom headers to send, such as User-Agent,
  447. If-None-Match, etc. If None, pool headers are used. If provided,
  448. these headers completely replace any pool-specific headers.
  449. :param retries:
  450. Configure the number of retries to allow before raising a
  451. :class:`~urllib3.exceptions.MaxRetryError` exception.
  452. Pass ``None`` to retry until you receive a response. Pass a
  453. :class:`~urllib3.util.retry.Retry` object for fine-grained control
  454. over different types of retries.
  455. Pass an integer number to retry connection errors that many times,
  456. but no other types of errors. Pass zero to never retry.
  457. If ``False``, then retries are disabled and any exception is raised
  458. immediately. Also, instead of raising a MaxRetryError on redirects,
  459. the redirect response will be returned.
  460. :type retries: :class:`~urllib3.util.retry.Retry`, False, or an int.
  461. :param redirect:
  462. If True, automatically handle redirects (status codes 301, 302,
  463. 303, 307, 308). Each redirect counts as a retry. Disabling retries
  464. will disable redirect, too.
  465. :param assert_same_host:
  466. If ``True``, will make sure that the host of the pool requests is
  467. consistent else will raise HostChangedError. When False, you can
  468. use the pool on an HTTP proxy and request foreign hosts.
  469. :param timeout:
  470. If specified, overrides the default timeout for this one
  471. request. It may be a float (in seconds) or an instance of
  472. :class:`urllib3.util.Timeout`.
  473. :param pool_timeout:
  474. If set and the pool is set to block=True, then this method will
  475. block for ``pool_timeout`` seconds and raise EmptyPoolError if no
  476. connection is available within the time period.
  477. :param release_conn:
  478. If False, then the urlopen call will not release the connection
  479. back into the pool once a response is received (but will release if
  480. you read the entire contents of the response such as when
  481. `preload_content=True`). This is useful if you're not preloading
  482. the response's content immediately. You will need to call
  483. ``r.release_conn()`` on the response ``r`` to return the connection
  484. back into the pool. If None, it takes the value of
  485. ``response_kw.get('preload_content', True)``.
  486. :param chunked:
  487. If True, urllib3 will send the body using chunked transfer
  488. encoding. Otherwise, urllib3 will send the body using the standard
  489. content-length form. Defaults to False.
  490. :param int body_pos:
  491. Position to seek to in file-like body in the event of a retry or
  492. redirect. Typically this won't need to be set because urllib3 will
  493. auto-populate the value when needed.
  494. :param \\**response_kw:
  495. Additional parameters are passed to
  496. :meth:`urllib3.response.HTTPResponse.from_httplib`
  497. """
  498. if headers is None:
  499. headers = self.headers
  500. if not isinstance(retries, Retry):
  501. retries = Retry.from_int(retries, redirect=redirect, default=self.retries)
  502. if release_conn is None:
  503. release_conn = response_kw.get("preload_content", True)
  504. # Check host
  505. if assert_same_host and not self.is_same_host(url):
  506. raise HostChangedError(self, url, retries)
  507. # Ensure that the URL we're connecting to is properly encoded
  508. if url.startswith("/"):
  509. url = six.ensure_str(_encode_target(url))
  510. else:
  511. url = six.ensure_str(parse_url(url).url)
  512. conn = None
  513. # Track whether `conn` needs to be released before
  514. # returning/raising/recursing. Update this variable if necessary, and
  515. # leave `release_conn` constant throughout the function. That way, if
  516. # the function recurses, the original value of `release_conn` will be
  517. # passed down into the recursive call, and its value will be respected.
  518. #
  519. # See issue #651 [1] for details.
  520. #
  521. # [1] <https://github.com/urllib3/urllib3/issues/651>
  522. release_this_conn = release_conn
  523. # Merge the proxy headers. Only do this in HTTP. We have to copy the
  524. # headers dict so we can safely change it without those changes being
  525. # reflected in anyone else's copy.
  526. if self.scheme == "http":
  527. headers = headers.copy()
  528. headers.update(self.proxy_headers)
  529. # Must keep the exception bound to a separate variable or else Python 3
  530. # complains about UnboundLocalError.
  531. err = None
  532. # Keep track of whether we cleanly exited the except block. This
  533. # ensures we do proper cleanup in finally.
  534. clean_exit = False
  535. # Rewind body position, if needed. Record current position
  536. # for future rewinds in the event of a redirect/retry.
  537. body_pos = set_file_position(body, body_pos)
  538. try:
  539. # Request a connection from the queue.
  540. timeout_obj = self._get_timeout(timeout)
  541. conn = self._get_conn(timeout=pool_timeout)
  542. conn.timeout = timeout_obj.connect_timeout
  543. is_new_proxy_conn = self.proxy is not None and not getattr(
  544. conn, "sock", None
  545. )
  546. if is_new_proxy_conn:
  547. self._prepare_proxy(conn)
  548. # Make the request on the httplib connection object.
  549. httplib_response = self._make_request(
  550. conn,
  551. method,
  552. url,
  553. timeout=timeout_obj,
  554. body=body,
  555. headers=headers,
  556. chunked=chunked,
  557. )
  558. # If we're going to release the connection in ``finally:``, then
  559. # the response doesn't need to know about the connection. Otherwise
  560. # it will also try to release it and we'll have a double-release
  561. # mess.
  562. response_conn = conn if not release_conn else None
  563. # Pass method to Response for length checking
  564. response_kw["request_method"] = method
  565. # Import httplib's response into our own wrapper object
  566. response = self.ResponseCls.from_httplib(
  567. httplib_response,
  568. pool=self,
  569. connection=response_conn,
  570. retries=retries,
  571. **response_kw
  572. )
  573. # Everything went great!
  574. clean_exit = True
  575. except queue.Empty:
  576. # Timed out by queue.
  577. raise EmptyPoolError(self, "No pool connections are available.")
  578. except (
  579. TimeoutError,
  580. HTTPException,
  581. SocketError,
  582. ProtocolError,
  583. BaseSSLError,
  584. SSLError,
  585. CertificateError,
  586. ) as e:
  587. # Discard the connection for these exceptions. It will be
  588. # replaced during the next _get_conn() call.
  589. clean_exit = False
  590. if isinstance(e, (BaseSSLError, CertificateError)):
  591. e = SSLError(e)
  592. elif isinstance(e, (SocketError, NewConnectionError)) and self.proxy:
  593. e = ProxyError("Cannot connect to proxy.", e)
  594. elif isinstance(e, (SocketError, HTTPException)):
  595. e = ProtocolError("Connection aborted.", e)
  596. retries = retries.increment(
  597. method, url, error=e, _pool=self, _stacktrace=sys.exc_info()[2]
  598. )
  599. retries.sleep()
  600. # Keep track of the error for the retry warning.
  601. err = e
  602. finally:
  603. if not clean_exit:
  604. # We hit some kind of exception, handled or otherwise. We need
  605. # to throw the connection away unless explicitly told not to.
  606. # Close the connection, set the variable to None, and make sure
  607. # we put the None back in the pool to avoid leaking it.
  608. conn = conn and conn.close()
  609. release_this_conn = True
  610. if release_this_conn:
  611. # Put the connection back to be reused. If the connection is
  612. # expired then it will be None, which will get replaced with a
  613. # fresh connection during _get_conn.
  614. self._put_conn(conn)
  615. if not conn:
  616. # Try again
  617. log.warning(
  618. "Retrying (%r) after connection broken by '%r': %s", retries, err, url
  619. )
  620. return self.urlopen(
  621. method,
  622. url,
  623. body,
  624. headers,
  625. retries,
  626. redirect,
  627. assert_same_host,
  628. timeout=timeout,
  629. pool_timeout=pool_timeout,
  630. release_conn=release_conn,
  631. chunked=chunked,
  632. body_pos=body_pos,
  633. **response_kw
  634. )
  635. # Handle redirect?
  636. redirect_location = redirect and response.get_redirect_location()
  637. if redirect_location:
  638. if response.status == 303:
  639. method = "GET"
  640. try:
  641. retries = retries.increment(method, url, response=response, _pool=self)
  642. except MaxRetryError:
  643. if retries.raise_on_redirect:
  644. response.drain_conn()
  645. raise
  646. return response
  647. response.drain_conn()
  648. retries.sleep_for_retry(response)
  649. log.debug("Redirecting %s -> %s", url, redirect_location)
  650. return self.urlopen(
  651. method,
  652. redirect_location,
  653. body,
  654. headers,
  655. retries=retries,
  656. redirect=redirect,
  657. assert_same_host=assert_same_host,
  658. timeout=timeout,
  659. pool_timeout=pool_timeout,
  660. release_conn=release_conn,
  661. chunked=chunked,
  662. body_pos=body_pos,
  663. **response_kw
  664. )
  665. # Check if we should retry the HTTP response.
  666. has_retry_after = bool(response.getheader("Retry-After"))
  667. if retries.is_retry(method, response.status, has_retry_after):
  668. try:
  669. retries = retries.increment(method, url, response=response, _pool=self)
  670. except MaxRetryError:
  671. if retries.raise_on_status:
  672. response.drain_conn()
  673. raise
  674. return response
  675. response.drain_conn()
  676. retries.sleep(response)
  677. log.debug("Retry: %s", url)
  678. return self.urlopen(
  679. method,
  680. url,
  681. body,
  682. headers,
  683. retries=retries,
  684. redirect=redirect,
  685. assert_same_host=assert_same_host,
  686. timeout=timeout,
  687. pool_timeout=pool_timeout,
  688. release_conn=release_conn,
  689. chunked=chunked,
  690. body_pos=body_pos,
  691. **response_kw
  692. )
  693. return response
  694. class HTTPSConnectionPool(HTTPConnectionPool):
  695. """
  696. Same as :class:`.HTTPConnectionPool`, but HTTPS.
  697. When Python is compiled with the :mod:`ssl` module, then
  698. :class:`.VerifiedHTTPSConnection` is used, which *can* verify certificates,
  699. instead of :class:`.HTTPSConnection`.
  700. :class:`.VerifiedHTTPSConnection` uses one of ``assert_fingerprint``,
  701. ``assert_hostname`` and ``host`` in this order to verify connections.
  702. If ``assert_hostname`` is False, no verification is done.
  703. The ``key_file``, ``cert_file``, ``cert_reqs``, ``ca_certs``,
  704. ``ca_cert_dir``, ``ssl_version``, ``key_password`` are only used if :mod:`ssl`
  705. is available and are fed into :meth:`urllib3.util.ssl_wrap_socket` to upgrade
  706. the connection socket into an SSL socket.
  707. """
  708. scheme = "https"
  709. ConnectionCls = HTTPSConnection
  710. def __init__(
  711. self,
  712. host,
  713. port=None,
  714. strict=False,
  715. timeout=Timeout.DEFAULT_TIMEOUT,
  716. maxsize=1,
  717. block=False,
  718. headers=None,
  719. retries=None,
  720. _proxy=None,
  721. _proxy_headers=None,
  722. key_file=None,
  723. cert_file=None,
  724. cert_reqs=None,
  725. key_password=None,
  726. ca_certs=None,
  727. ssl_version=None,
  728. assert_hostname=None,
  729. assert_fingerprint=None,
  730. ca_cert_dir=None,
  731. **conn_kw
  732. ):
  733. HTTPConnectionPool.__init__(
  734. self,
  735. host,
  736. port,
  737. strict,
  738. timeout,
  739. maxsize,
  740. block,
  741. headers,
  742. retries,
  743. _proxy,
  744. _proxy_headers,
  745. **conn_kw
  746. )
  747. self.key_file = key_file
  748. self.cert_file = cert_file
  749. self.cert_reqs = cert_reqs
  750. self.key_password = key_password
  751. self.ca_certs = ca_certs
  752. self.ca_cert_dir = ca_cert_dir
  753. self.ssl_version = ssl_version
  754. self.assert_hostname = assert_hostname
  755. self.assert_fingerprint = assert_fingerprint
  756. def _prepare_conn(self, conn):
  757. """
  758. Prepare the ``connection`` for :meth:`urllib3.util.ssl_wrap_socket`
  759. and establish the tunnel if proxy is used.
  760. """
  761. if isinstance(conn, VerifiedHTTPSConnection):
  762. conn.set_cert(
  763. key_file=self.key_file,
  764. key_password=self.key_password,
  765. cert_file=self.cert_file,
  766. cert_reqs=self.cert_reqs,
  767. ca_certs=self.ca_certs,
  768. ca_cert_dir=self.ca_cert_dir,
  769. assert_hostname=self.assert_hostname,
  770. assert_fingerprint=self.assert_fingerprint,
  771. )
  772. conn.ssl_version = self.ssl_version
  773. return conn
  774. def _prepare_proxy(self, conn):
  775. """
  776. Establish tunnel connection early, because otherwise httplib
  777. would improperly set Host: header to proxy's IP:port.
  778. """
  779. conn.set_tunnel(self._proxy_host, self.port, self.proxy_headers)
  780. conn.connect()
  781. def _new_conn(self):
  782. """
  783. Return a fresh :class:`httplib.HTTPSConnection`.
  784. """
  785. self.num_connections += 1
  786. log.debug(
  787. "Starting new HTTPS connection (%d): %s:%s",
  788. self.num_connections,
  789. self.host,
  790. self.port or "443",
  791. )
  792. if not self.ConnectionCls or self.ConnectionCls is DummyConnection:
  793. raise SSLError(
  794. "Can't connect to HTTPS URL because the SSL module is not available."
  795. )
  796. actual_host = self.host
  797. actual_port = self.port
  798. if self.proxy is not None:
  799. actual_host = self.proxy.host
  800. actual_port = self.proxy.port
  801. conn = self.ConnectionCls(
  802. host=actual_host,
  803. port=actual_port,
  804. timeout=self.timeout.connect_timeout,
  805. strict=self.strict,
  806. cert_file=self.cert_file,
  807. key_file=self.key_file,
  808. key_password=self.key_password,
  809. **self.conn_kw
  810. )
  811. return self._prepare_conn(conn)
  812. def _validate_conn(self, conn):
  813. """
  814. Called right before a request is made, after the socket is created.
  815. """
  816. super(HTTPSConnectionPool, self)._validate_conn(conn)
  817. # Force connect early to allow us to validate the connection.
  818. if not getattr(conn, "sock", None): # AppEngine might not have `.sock`
  819. conn.connect()
  820. if not conn.is_verified:
  821. warnings.warn(
  822. (
  823. "Unverified HTTPS request is being made to host '%s'. "
  824. "Adding certificate verification is strongly advised. See: "
  825. "https://urllib3.readthedocs.io/en/latest/advanced-usage.html"
  826. "#ssl-warnings" % conn.host
  827. ),
  828. InsecureRequestWarning,
  829. )
  830. def connection_from_url(url, **kw):
  831. """
  832. Given a url, return an :class:`.ConnectionPool` instance of its host.
  833. This is a shortcut for not having to parse out the scheme, host, and port
  834. of the url before creating an :class:`.ConnectionPool` instance.
  835. :param url:
  836. Absolute URL string that must include the scheme. Port is optional.
  837. :param \\**kw:
  838. Passes additional parameters to the constructor of the appropriate
  839. :class:`.ConnectionPool`. Useful for specifying things like
  840. timeout, maxsize, headers, etc.
  841. Example::
  842. >>> conn = connection_from_url('http://google.com/')
  843. >>> r = conn.request('GET', '/')
  844. """
  845. scheme, host, port = get_host(url)
  846. port = port or port_by_scheme.get(scheme, 80)
  847. if scheme == "https":
  848. return HTTPSConnectionPool(host, port=port, **kw)
  849. else:
  850. return HTTPConnectionPool(host, port=port, **kw)
  851. def _normalize_host(host, scheme):
  852. """
  853. Normalize hosts for comparisons and use with sockets.
  854. """
  855. host = normalize_host(host, scheme)
  856. # httplib doesn't like it when we include brackets in IPv6 addresses
  857. # Specifically, if we include brackets but also pass the port then
  858. # httplib crazily doubles up the square brackets on the Host header.
  859. # Instead, we need to make sure we never pass ``None`` as the port.
  860. # However, for backward compatibility reasons we can't actually
  861. # *assert* that. See http://bugs.python.org/issue28539
  862. if host.startswith("[") and host.endswith("]"):
  863. host = host[1:-1]
  864. return host